package com.orangelife.mobile.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.jump.CommonJumper;
import com.curry.android.http.HttpUtil;
import com.curry.android.net.NetworkUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.buyFresh.adapter.BuyFreshGridViewAdapter;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.login.activity.Login2Activity;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.verify.biz.SmsHttpBiz;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
@Deprecated
public class BuyOrRegisterPopupWindow extends PopupWindow {
	
	private View mMenuView;
	/** 商品图片*/
	private ImageView ivPhoto;
	/** 现价*/
	private TextView tvPriceDiscount;
	/** 原价*/
	private TextView tvPrice;
	/** 选重*/
	private TextView tvWeight;
	/** gridview*/
	private GridView gvWeight;
	/** 减号*/
	private ImageButton ibMinus;
	/** 加号*/
	private ImageButton ibPlus;
	/** 数量*/
	private TextView tvCount;
	/** 购买按钮*/
	private Button btnBuy;
	/** 手机号*/
	private EditText etPhone;
	/** 验证码*/
	private EditText etIdentify;
	/** 发送验证码*/
	private Button btnSend;
	/** 登录*/
	private TextView tvLogin;
	/** 地址*/
	private LinearLayout llAddress;
	/** 提交订单*/
	private Button btnSubmit;
	/** 关闭*/
	private ImageButton ibClose;
	/** 取消*/
	private ImageButton ibCancel;
	/** 购买relativelayout*/
	private RelativeLayout rlBuy;
	/** 注册Relativelayout*/
	private RelativeLayout llRegister;
	/** 免注册登录*/
	private LinearLayout llNoRegister;
	/** 登录*/
	private LinearLayout llLogin;
	/** 注册登录之间的view*/
	private View view;
	
	private List<Map<String,Object>> listSpecification;
	/** 商品数量 */
	private int count;
	/** 是否选择成功 */
	private int flag = 0;
	private Context context;
	private Map<String,Object> map;
	
	private Dialog dialog;
	
	private int timeSendSms = 59;
	private Timer timer;
	
	/** 发送验证码 */
	private Button btnSendIdentify;
	/**上次的选择*/
	private int positionLast = 0;
	/**那个部分传过来的（1是生鲜，2是团购，3是线下活动）*/
	private int active;
	
	public BuyOrRegisterPopupWindow(final Activity context,int active,List<Map<String,Object>> list) {
		super(context);
		this.context = context;
		this.listSpecification = list;
		this.active = active;
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mMenuView = inflater.inflate(R.layout.dialog_order_register, null);
		ivPhoto = (ImageView)mMenuView.findViewById(R.id.ivPhoto);
		tvPriceDiscount = (TextView)mMenuView.findViewById(R.id.tvPriceDiscount);
		tvPrice = (TextView)mMenuView.findViewById(R.id.tvPrice);
		tvWeight = (TextView)mMenuView.findViewById(R.id.tvWeight);
		gvWeight = (GridView)mMenuView.findViewById(R.id.gvSpecification);
		ibClose = (ImageButton)mMenuView.findViewById(R.id.ibClose);
		ibMinus = (ImageButton)mMenuView.findViewById(R.id.ibDelete);
		ibPlus = (ImageButton)mMenuView.findViewById(R.id.ibPlus);
		tvCount = (TextView)mMenuView.findViewById(R.id.tvCount);
		btnBuy = (Button)mMenuView.findViewById(R.id.btnBuy);
		
		etPhone = (EditText)mMenuView.findViewById(R.id.etPhone);
		etIdentify = (EditText)mMenuView.findViewById(R.id.etIdentify);
		btnSend = (Button)mMenuView.findViewById(R.id.btnSendIdentify);
		tvLogin = (TextView)mMenuView.findViewById(R.id.tvRepairLogin);
		llAddress = (LinearLayout)mMenuView.findViewById(R.id.llAddAddress);
		ibCancel = (ImageButton)mMenuView.findViewById(R.id.ibCancel);
		btnSubmit = (Button)mMenuView.findViewById(R.id.btnSubmit);
		
		rlBuy = (RelativeLayout)mMenuView.findViewById(R.id.rlBuy);
		llRegister = (RelativeLayout)mMenuView.findViewById(R.id.rlRegister);
		llNoRegister = (LinearLayout)mMenuView.findViewById(R.id.llIdentify);
		llLogin = (LinearLayout)mMenuView.findViewById(R.id.llLogin);
		view = (View)mMenuView.findViewById(R.id.view1);
		//取消按钮
		ibClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//销毁弹出框
				dismiss();
			}
		});
		//取消按钮
		ibCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//销毁弹出框
				dismiss();
			}
		});
		tvCount.setText(1+"");
		if(active == 2 || active == 3){
			llRegister.setVisibility(View.VISIBLE);
			rlBuy.setVisibility(View.GONE);
		}else if(active == 1){
			BuyFreshGridViewAdapter adapter = new BuyFreshGridViewAdapter(context, listSpecification, positionLast,false);
			gvWeight.setAdapter(adapter);
			tvPriceDiscount.setText(Constant.RMB_FLAG+listSpecification.get(0).get("price").toString());
			tvPrice.setText(Constant.RMB_FLAG+listSpecification.get(0).get("mkPrice").toString());
			tvPrice.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG);
			tvWeight.setText(listSpecification.get(0).get("pdtDesc").toString());
		}
		
		gvWeight.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
			 TextView tvSelectWeight = (TextView) view.findViewById(R.id.tvWeight);
			 BuyFreshGridViewAdapter adapter = new BuyFreshGridViewAdapter(context, listSpecification, position,false);
			 gvWeight.setAdapter(adapter);
			 tvPrice.setText(Constant.RMB_FLAG+listSpecification.get(position).get("mkPrice").toString());
			 tvPriceDiscount.setText(Constant.RMB_FLAG+listSpecification.get(position).get("price").toString());
			 tvWeight.setText(listSpecification.get(position).get("pdtDesc").toString());
			 positionLast = position;
			}
		});
		
		
		ibMinus.setOnClickListener(itemsOnClick);
		ibPlus.setOnClickListener(itemsOnClick);
		btnBuy.setOnClickListener(itemsOnClick);
		
		btnSend.setOnClickListener(itemsOnClick);
		tvLogin.setOnClickListener(itemsOnClick);
		llAddress.setOnClickListener(itemsOnClick);
		btnSubmit.setOnClickListener(itemsOnClick);
		//设置SelectPicPopupWindow的View
		this.setContentView(mMenuView);
		//设置SelectPicPopupWindow弹出窗体的宽
		this.setWidth(LayoutParams.FILL_PARENT);
		//设置SelectPicPopupWindow弹出窗体的高
		this.setHeight(LayoutParams.WRAP_CONTENT);
		//设置SelectPicPopupWindow弹出窗体可点击
		this.setFocusable(true);
		//设置SelectPicPopupWindow弹出窗体动画效果
		this.setAnimationStyle(R.style.AnimBottom);
		//实例化一个ColorDrawable颜色为半透明
		ColorDrawable dw = new ColorDrawable(0xb0000000);
		//设置SelectPicPopupWindow弹出窗体的背景
		this.setBackgroundDrawable(dw);
		this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		//mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
		mMenuView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				int height = mMenuView.findViewById(R.id.pop_layout).getTop();
				int y=(int) event.getY();
				if(event.getAction()==MotionEvent.ACTION_UP){
					if(y<height){
						dismiss();
					}
				}				
				return true;
			}
		});

	}
	
	private Handler handler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
				.get("errInfo").toString();
				if (errInfo.equals("OK")){
					DialogHelper.closeDialog(dialog);
					dismiss();
					ToastHelper.getInstance()._toast(context.getResources().getString(R.string.submit_success));
				}else{
					DialogHelper.closeDialog(dialog);
					ToastHelper.getInstance()._toast(
							context.getResources().getString(
									R.string.validation_fail_info));
				}
				break;
			case Constant.WHAT_ERROR_HTTP:
				ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
				break;

			default:
				break;
			}
		}
	};
	
	
	
	private OnClickListener itemsOnClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.ibDelete:
				count = Integer.parseInt(tvCount.getText().toString());
				if(count > 1){
					count--;
					tvCount.setText(count+"");
				}
				count = Integer.parseInt(tvCount.getText().toString());
				if(count <2){
					ibMinus.setBackgroundResource(R.drawable.count_delete_gray);
				}
				
				break;
			case R.id.ibPlus:
				count = Integer.parseInt(tvCount.getText().toString());
				count ++;
				tvCount.setText(count+"");
				count = Integer.parseInt(tvCount.getText().toString());
				if(count>1){
					ibMinus.setBackgroundResource(R.drawable.count_delete);
				}
				break;
			case R.id.btnBuy:
				
					if(isRegister()){
						setOrder();
					}else{
						rlBuy.setVisibility(View.GONE);
						llRegister.setVisibility(View.VISIBLE);
					}
				
				break;
			case R.id.btnSendIdentify:
				String phone = etPhone.getText().toString();
				if (StringUtil.isContainBlank(phone)) {
					ToastHelper.getInstance().displayToastWithQuickClose(
							context.getResources().getString(
									R.string.register_phone_null));
				} else if (!StringUtil.isPhone(phone)) {
					ToastHelper.getInstance().displayToastWithQuickClose(
							context.getResources().getString(
									R.string.register_phone_error));
				} else {
					if (isConnected()) {
						dialog = DialogHelper.getInstance().createLoadingDialog(
								context,
								context.getResources().getString(
										R.string.register_request_vercode));
						dialog.show();
						sendRequestForCode(phone);
						countDownSendSmsAgain();
					}
				}
				break;
			case R.id.tvRepairLogin:
				CommonJumper.jumpToLogin(context);
				break;
			case R.id.llAddAddress:
				break;
			case R.id.btnSubmit:
				if(!isRegister()){
					rlBuy.setVisibility(View.GONE);
					llRegister.setVisibility(View.VISIBLE);
				}else{
					if(isFillAddress()){
						//提交
						setOrder();
					}else{
						view.setVisibility(view.GONE);
						llNoRegister.setVisibility(view.GONE);
						llLogin.setVisibility(view.GONE);
					}
					
					
				}
				break;

			default:
				break;
			}
			
		}
	};
	
	private boolean isRegister(){
		return true;
	}
	private boolean isFillAddress(){
		return true;
		
	}
	
	/**
	 * 发送验证码请求
	 * 
	 * @param phone
	 *            手机
	 */
	private void sendRequestForCode(String phone) {
		SmsHttpBiz.getSmsCodeOld(phone, "1", handler, 0);
	}
	
	/**
	 * 重置验证码时间
	 */
	private void countDownSendSmsAgain() {
		/* 点击发送验证码后进行倒计时 */
		timeSendSms = 59;
		btnSendIdentify.setEnabled(false);
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				mHandler.obtainMessage(Constant.WHAT_COUNT_DOWN, timeSendSms--)
						.sendToTarget();
			}
		}, 0, 1000);
	}
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Constant.WHAT_COUNT_DOWN:
				if (timeSendSms >= 0) {
					btnSendIdentify.setText(context.getResources().getString(R.string.wait)
							+ timeSendSms
							+ context.getResources().getString(R.string.seconds));
				} else {
					btnSendIdentify.setEnabled(true);
					btnSendIdentify.setText(context.getResources().getString(
							R.string.send_again));
					timer.cancel();
				}
				break;
			default:
				break;
			}
		}

	};
	
	
	/**
	 * 是否联网
	 * 
	 * @return true-联网，false-断网；
	 */
	protected boolean isConnected() {
		if (!NetworkUtil.isConnectedNet(context)) {
			Toast.makeText(context,
					context.getResources().getString(R.string.net_disconnected),
					Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
	
	/** 将添加的数据上传上去 */
	private void setOrder() {
		try {
			map = new HashMap<String, Object>();
			if(active == 1){
				map.put("sellPloyID", listSpecification.get(positionLast).get("sellPloyID").toString());
				map.put("productID", listSpecification.get(positionLast).get("productID").toString());
				map.put("orderNumber", tvCount.getText().toString());
				map.put("shipName", "张三");
				map.put("shipPhone", "15306022224");
				map.put("shipAddr", "软件大道");
			}else if(active == 3){
				map.put("actvtID", listSpecification.get(positionLast).get("actvtID"));
				map.put("sellPloyID", listSpecification.get(positionLast).get("sellPloyID").toString());
				map.put("productID", listSpecification.get(positionLast).get("productID").toString());
				map.put("orderNumber", tvCount.getText().toString());
				map.put("shipName", "张三");
				map.put("shipPhone", "15306022224");
				map.put("shipAddr", "软件大道");
			}else if(active == 2){
				map.put("actvtID", listSpecification.get(positionLast).get("actvtID").toString());
				map.put("shipPhone", "15306022224");
			}
			
			Map<String, Object> rootMap = new HashMap<String, Object>();
			rootMap.put("map", map);
			if(active == 1){
				rootMap.put("url", Constant.URL_BUYFRESH_ADD);
			}else if(active == 3){
				rootMap.put("url", Constant.URL_GROUP_ADD);
			}else if(active == 2){
				rootMap.put("url", Constant.URL_UNDERLINE_ADD);
			}
			rootMap.put("wat", 0);
			new JSONRequest(JSONRequest.POST, rootMap, handler,
					HttpUtil.ACTION_JSON);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
